#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : 龍皓
# @time    : 2024/12/19 09:02
# @function: cordCloud自动签到脚本
# @version : 1.0.1
import re
from playwright.sync_api import sync_playwright
from settings import CORD_CLOUD_CREDENTIALS
from utils.logUtil import get_logger

# 获取日志对象
logger = get_logger()

class CordCloudSignIn:
    def __init__(self):
        self.playwright = None
        self.browser = None
        self.context = None
        self.page = None

    def run(self):
        cord_cloud_url = CORD_CLOUD_CREDENTIALS.get("url")
        cord_cloud_username = CORD_CLOUD_CREDENTIALS.get("username")
        cord_cloud_password = CORD_CLOUD_CREDENTIALS.get("password")
        if cord_cloud_url == "":
            logger.error("cordCloud域名为空，请先填写！")
            return
        if cord_cloud_username == "" or cord_cloud_password == "":
            logger.error("邮箱或密码为空，请先填写！")
            return

        self.playwright = sync_playwright().start()
        self.browser = self.playwright.chromium.launch(headless=False)
        self.context = self.browser.new_context()
        # 打开新页面
        self.page = self.context.new_page()
        self.page.set_viewport_size({"width": 1920, "height": 1080})
        # 打开网址
        login_url = cord_cloud_url + "/auth/login"
        self.page.goto(login_url)
        logger.info("正在打开网址:" + login_url)
        # 输入账号密码
        self.page.get_by_label("邮箱").fill(cord_cloud_username)
        self.page.get_by_label("密码").fill(cord_cloud_password)
        self.page.get_by_role("button", name="确认登录").click()
        logger.info("输入账号密码完成。")

        if self.page.locator("text=知道了").is_visible():
            logger.info("按钮可见，尝试点击...")
            self.page.locator("text=知道了").click()
        else:
            logger.info("按钮不可见，跳过操作。")

        # 等待跳转到用户页面
        self.page.wait_for_url(cord_cloud_url + "/user")
        logger.info("等待用户页面加载...")

        try:
            # 检查签到状态
            if self.page.is_visible("div.card-action div.usercheck p a"):
                # 签到状态
                self.page.wait_for_selector("div.card-action div.usercheck p a", timeout=10000)
                sign_status_text = self.page.locator("div.card-action div.usercheck p a").inner_text()
                # 去掉 "check" 和空格
                cleaned_text = sign_status_text.replace("check", "").strip()

                # 今日已用
                used_today_text = self.page.locator("code.card-tag.tag-red").inner_text()
                # 过去已用
                used_past_text = self.page.locator("code.card-tag.tag-orange").inner_text()
                # 剩余流量
                residual_text = self.page.locator("#remain").inner_text()

                # 定位上次签到时间的 <p> 标签
                last_checkin_text = self.page.locator("p:has-text('上次签到时间')").inner_text()

                # 提取时间部分
                last_checkin_time = last_checkin_text.split("：")[1].strip()

                logger.info(f"【今日已用】: {used_today_text}")
                logger.info(f"【过去已用】: {used_past_text}")
                logger.info(f"【剩余流量】: {residual_text}")
                logger.info(f"【签到状态】: {cleaned_text}")
                logger.info(f"【上次签到时间】: {last_checkin_time}")
            else:
                try:
                    logger.info("正在检测签到按钮是否存在...")
                    # 检查签到按钮是否存在
                    if self.page.is_visible("//*[@id='checkin']"):
                        # 等待第一个签到按钮出现并执行点击
                        self.page.wait_for_selector("//*[@id='checkin']", timeout=5000)
                        sign_in_text = self.page.locator("//*[@id='checkin']").inner_text()

                        sign_in_text = sign_in_text.replace("check", "").replace("screen_rotation", "").replace(" ", "").strip()

                        self.page.locator("//*[@id='checkin']").click()
                        # 处理可能出现的弹窗
                        if self.page.is_visible("text=知道了"):
                            self.page.locator("text=知道了").click()

                        try:
                            # 等待弹窗出现
                            self.page.wait_for_selector("div.modal-dialog.modal-xs", timeout=5000)

                            # 获取弹窗中的文本内容
                            modal_text = self.page.locator("#msg").inner_text()

                            # 提取字母和数字部分
                            flow_rate_text = re.sub(r"[^a-zA-Z0-9]", "", modal_text)

                            logger.info("今日获取流量为: " + flow_rate_text)
                        except Exception as e:
                            logger.error("弹窗不可见或未包含预期文本: {e}")

                        logger.info("【点击签到完成】")
                    else:
                        logger.warning("签到按钮不存在，可能已经签到或页面异常")
                except Exception as e:
                    logger.error("签到异常:" + str(e))
        except Exception as e:
            logger.error("检查签到状态时异常:" + str(e))

        self.close()

    def close(self):
        if self.page:
            self.page.close()
        if self.context:
            self.context.close()
        if self.browser:
            self.browser.close()
        if self.playwright:
            self.playwright.stop()


if __name__ == '__main__':
    sign_in = CordCloudSignIn()
    sign_in.run()